<?php

namespace app\common\controller;

use app\api\consDir\ErrorConst;
use app\api\provider\Userinfo;
use app\BaseController;
use app\common\utils\CommonUtil;
use think\App;
use think\exception\HttpResponseException;
use think\facade\Log;
use think\helper\Arr;
use think\Response;

class RestController extends BaseController
{
    //不需要登录节点
    protected $noNeedLogin = ['*'];

    //用户信息
    private $userinfo = [];

    //参数
    public $param = [];

    /**
     * RestController constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        if (!Userinfo::getInstance()->match($this->noNeedLogin, $this->request) && !$this->app->userinfo->id) {
            CommonUtil::throwException(ErrorConst::NOT_LOGIN_ERROR, ErrorConst::NOT_LOGIN_ERROR_MSG);
        }
        $this->param = input();
    }

    /**
     * @param $param
     */
    public function checkParam($param)
    {
        foreach ($param as $k => $v) {
            if (!isset($this->param[$v])) {
                $this->result(ErrorConst::BASE_ERROR);
            }
        }
    }


    /**
     * 返回
     * @param null $data
     */
    public function result($data = null)
    {
        is_object($data) && $data = objectToArray($data);
        $code = $data['code'] ?? ErrorConst::SUCCESS_CODE;
        $msg = $data['msg'] ?? ErrorConst::SUCCESS_CODE_MSG;
        $rData = empty($data) ? new \stdClass() : (is_object($data) ? $data->toArray() : $data);
        if (!is_array($data) && !is_object($data)) {
            $rData = new \stdClass();
            if (is_numeric($data)) {
                $code = $data;
            } elseif ($data !== true) {
                $code = ErrorConst::BASE_ERROR;
                $msg = $data;
                $rData = new \stdClass();
            } elseif ($data == true) {
                $rData = new \stdClass();
            }
        }
        CommonUtil::response($code, $msg, $rData);
        return true;
    }
}